<template>
    <div class="app-container" v-loading="imageLoading">
        <el-tabs v-model="currentTab" type="card" class="center-tabs" @tab-click="tabHandleClick">
            <el-tab-pane label="录入检测指标" name="dectionAdd" />
            <el-tab-pane label="已检测指标" name="dectionDetail" v-if="baseAdd.isDetail&&baseAdd.isShow!=1">
            <span slot="label">
                已检测指标
                <el-badge v-if="Listtotal > 0" :value="Listtotal"
                    class="tab-content-badge"></el-badge>
            </span>
        </el-tab-pane>
        </el-tabs>
        <div>

            <el-form class="formBox formBox1" :model="queryParams" ref="queryForm" size="small" :inline="true"
                label-width="68px" :rules="rules">
                <el-form-item label="顾客编号" prop="visitNum">
                    <el-input v-model="queryParams.visitNum" placeholder="请输入顾客编号" clearable style="width: 160px"
                        :disabled="baseAdd.updateStatus || baseAdd.isDetail" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="姓名" prop="patientName" label-width="40px">
                    <el-input v-model="queryParams.patientName" placeholder="请输入顾客姓名" clearable style="width: 160px"
                        :disabled="baseAdd.updateStatus || baseAdd.isDetail" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                        v-if="!baseAdd.updateStatus && !baseAdd.isDetail">搜索</el-button>
                </el-form-item>
            </el-form>
            <div v-show="currentTab === 'dectionAdd'">
                <el-form :model="projectForm" ref="projectForm" size="small" :inline="true" label-width="68px">
                    <div class="formBox">
                        <el-row v-if="!baseAdd.updateStatus">
                            <el-col :span="12">
                                <div>
                                    <el-form-item label="选择检测设备" prop="mealId" label-width="100px">
                                        <el-select v-model="projectForm.deviceId" placeholder="下拉选择之后点击加入" clearable
                                            style="width:200px">
                                            <el-option v-for="item in deviceList" :key="item.deviceId"
                                                :label="item.deviceName" :value="item.deviceId" />
                                        </el-select>
                                        <el-button size="mini" @click="addPackage" type="primary"
                                            style="margin-left:10px;">加入</el-button>
                                    </el-form-item>
                                </div>

                            </el-col>
                            <el-col :span="12">
                                <div>
                                    <el-form-item label="添加检测单项" prop="planCategoryId" clearable label-width="100px">
                                        <el-select v-model="projectForm.detectionId" placeholder="请选择检测单项点击加入" clearable
                                            style="width: 200px">
                                            <el-option v-for="dict in detectionType" :key="dict.detectionId"
                                                :label="dict.detectionName" :value="dict.detectionId"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="" prop="planId">
                                        <el-button size="mini" @click="addSingle" type="primary"
                                            style="margin-left:10px;">加入</el-button>
                                    </el-form-item>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <div style="margin-top:10px;">
                                <el-table :data="tableData" stripe style="width: 100%">
                                    <el-table-column prop="detectionName" label="指标名称" width="180">
                                    </el-table-column>
                                    <el-table-column prop="detectionValue" label="检测值" width="180">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.detectionValue" placeholder="默认值"
                                                v-if="scope.row.detectionType == '0'"></el-input>
                                            <el-select v-model="scope.row.detectionValue" placeholder="请选择" clearable
                                                v-if="scope.row.detectionType == '1'">
                                                <el-option v-for="dict in getValueStr(scope.row.valueStr)" :key="dict"
                                                    :label="dict" :value="dict"></el-option>
                                            </el-select>

                                            <!-- <el-input v-model="scope.row.defaultValue" placeholder="默认值" ></el-input> -->
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="detectionUnit" label="单位">
                                        <template slot-scope="scope">
                                            <span v-if="scope.row.detectionUnit">{{ scope.row.detectionUnit }}</span>
                                            <span v-else>-</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="hightValue" label="正常值范围">
                                        <template slot-scope="scope">
                                            <span v-if="scope.row.detectionType == '0'">{{ scope.row.limitValue }} ~
                                                {{ scope.row.hightValue }}</span>
                                            <span v-else>-</span>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column prop="remark" label="备注">
                            </el-table-column> -->
                                </el-table>
                            </div>
                        </el-row>
                    </div>
                </el-form>
                <el-button class="detectionAddbtn" @click="submitEvent">提交</el-button>
            </div>
            <div v-show="currentTab === 'dectionDetail'">
                <el-table border v-loading="loading" style="width: 100%" :data="listDetectionVisit">
                    <el-table-column label="序号" align="center" type="index" width="50">
                        <template slot-scope="scope">
                            <span>{{ getDetectionIndexFormIndex(scope.$index) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="顾客编号" align="center" prop="visitNum" width="160">
                    </el-table-column>
                    <el-table-column label="顾客姓名" align="center" prop="patientName" :show-overflow-tooltip="true"
                        width="100" />
                    <el-table-column label="检测指标" align="center" prop="visitDetectionName">
                    </el-table-column>
                    <el-table-column label="检测值" align="center" prop="detectionValue" :show-overflow-tooltip="true"
                        width="160" />
                    <el-table-column label="异常标志" align="center" prop="defaultValue" :show-overflow-tooltip="true"
                        width="120">
                        <template slot-scope="scope">
                            <span :style="{ color: getLabel(scope.row) == '异常' ? 'red' : 'green' }">{{
                                getLabel(scope.row) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="正常值" align="center" prop="defaultValue" :show-overflow-tooltip="true"
                        width="120">
                        <template slot-scope="scope">
                            <span v-if="scope.row.hightValue != '' && scope.row.hightValue != null">{{
                                scope.row.limitValue }} ~
                                {{ scope.row.hightValue }}</span>
                            <span
                                v-else-if="(scope.row.hightValue == '' || scope.row.hightValue == null) && scope.row.defaultValue != '' && scope.row.defaultValue != null">{{
                                    scope.row.defaultValue }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="检测医生" align="center" prop="createBy">

                    </el-table-column>
                    <el-table-column sortable label="检测日期" align="center" prop="createTime">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="Listtotal > 0" :total="Listtotal" :page.sync="detectionIndexForm.pageNum"
                    :limit.sync="detectionIndexForm.pageSize" @pagination="getlistDetectionVisit" />
            </div>

        </div>
        <el-dialog title="选择顾客" :visible.sync="patientVisible" width="80%" :close-on-click-modal="false" v-dialogDrag
            append-to-body>
            <div class="formBox">
                <el-table border v-loading="loading" style="width: 100%" :data="patientList">
                    <el-table-column label="序号" align="center" type="index" width="50">
                        <template slot-scope="scope">
                            <span>{{ getIndex(scope.$index) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="顾客编号" align="center" prop="visitNum" width="160" />
                    <el-table-column sortable label="顾客姓名" align="center" prop="patientName" :show-overflow-tooltip="true"
                        width="100" />
                    <el-table-column sortable label="顾客手机号" align="center" prop="patientPhone" :show-overflow-tooltip="true"
                        width="120" />
                    <el-table-column sortable label="顾客身份证号" align="center" prop="idNum" :show-overflow-tooltip="true"
                        width="180" />
                    <el-table-column sortable label="性别" align="center" prop="sex" width="80">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="年龄" align="center" prop="birthDate" width="80">
                        <template slot-scope="scope">
                            <span>{{ parseInt((new Date() - new Date(parseTime(scope.row.birthDate))) / (1000 * 60 * 60 * 24
                                * 365))
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column sortable label="就诊门诊" align="center" prop="deptName" :show-overflow-tooltip="true"
                        width="160" />

                    <el-table-column sortable label="状态" align="center" prop="status" :show-overflow-tooltip="true"
                        width="120">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
                        </template>
                    </el-table-column>
                    <!--            <el-table-column sortable label="卡号" align="center" prop="cardNumber" :show-overflow-tooltip="true" />-->

                    <el-table-column sortable label="顾客性质" align="center" prop="properties" width="100">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_patient_properties" :value="scope.row.properties" />
                        </template>
                    </el-table-column>
                    <!--            <el-table-column sortable label="顾客分类" align="center" prop="customerSort" width="100">-->
                    <!--              <template slot-scope="scope">-->
                    <!--                <dict-tag :options="dict.type.sys_patient_sort" :value="scope.row.customerSort" />-->
                    <!--              </template>-->
                    <!--            </el-table-column>-->
                    <!--            <el-table-column label="诊断" align="center" prop="diagnosis" />-->

                    <el-table-column sortable label="登记人" align="center" prop="createBy" width="100"
                        :show-overflow-tooltip="true" />
                    <el-table-column sortable label="登记日期" align="center" prop="createTime" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width"
                        width="100">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-caret-right"
                                @click="confirmPatient(scope.row)">点击选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :pageSizes.sync="pageSizes" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getPatientList" />
            </div>
        </el-dialog>
    </div>
</template>

<script>

import { getVisit } from "@/api/patientRegistration/registrationList";
import { listDetectionVisit, addDetectionVisit, listNotHaveDevice, updateDetectionVisit } from "@/api/photoWorkstation/detection";
import {listDevice, getDevice, listDeviceDept} from "@/api/system/device";
import { listDetection, getDetection } from "@/api/system/detection";

export default {
    name: "detectionAdd",
    components: {
    },
    dicts: [
        "sys_diagnosis_status",
        "sys_user_sex",
        "sys_face_part",
        "sys_patient_properties",
        "sys_patient_sort",
        "sys_diagnosis_status"
    ],
    props: ['baseAdd'],
    data() {
        return {
            listDetectionVisit: [],
            detectionIndexForm: {
                pageNum: 1,
                pageSize: 10,
                visitNum: '',
                patientId: ''
            },
            Listtotal: 0,
            patientVisible: false,
            imageLoading: false,
            loading: false,
            queryParams: {
                pageNum: 1,
                pageSize: 5,
                visitNum: undefined,
                patientName: undefined,
                patientId: undefined,
            },
            total: 0,
            pageSizes: [5, 10, 15, 20],
            patientList: [],
            tableData: [],
            projectForm: {
                deviceId: '',
                detectionId: ''
            },
            // 表单校验
            rules: {
                patientName: [
                    {
                        required: true,
                        message: "顾客姓名不能为空",
                    },
                ],
                visitNum: [
                    {
                        required: true,
                        message: "顾客编号不能为空",
                    },
                ],
            },
            deviceList: [],//设备
            detectionType: [],//单项
            detectionArr: [],//数组存储
            currentTab: "dectionAdd"
        };
    },
    created() {

    },
    mounted() {
        console.log("谈")
        console.log(this.baseAdd)
        if (this.baseAdd.updateStatus || this.baseAdd.isDetail) {
            this.queryParams.visitNum = this.baseAdd.visitNum
            this.queryParams.patientName = this.baseAdd.patientName
            this.queryParams.patientId = this.baseAdd.patientId
            this.detectionIndexForm.visitNum = this.baseAdd.visitNum
            this.detectionIndexForm.patientId = this.baseAdd.patientId
            if (this.baseAdd.updateStatus) {
                let arr = []
                let data = this.baseAdd
                data.detectionName = data.visitDetectionName

                if (data.detectionType=='0') {//文本值

                    arr[0] = data
                    this.tableData = arr
                } else if (data.detectionType=='1') {

                    arr[0] = data
                    this.getDetection(data, arr)
                }
            }
            if (this.baseAdd.isDetail) {
                this.tableData = []
                this.getlistDetectionVisit()
            }



        } else {
            // this.queryParams.visitNum=''
            this.tableData = []
        }
        this.getDeviceList()
        this.getDetectionList()
    },
    methods: {
        getLabel(row) {
            let labeltext = ''
            if (row.hightValue != '' && row.hightValue != null && row.limitValue != '' && row.limitValue != null) {//文本值
                if ((Number(row.hightValue) >= Number(row.detectionValue)) && (Number(row.detectionValue) >= Number(row.limitValue))) {
                    labeltext = '正常'
                } else {
                    labeltext = '异常'
                }
            } else if ((row.hightValue == '' || row.hightValue == null) && row.defaultValue != '' && row.defaultValue != null) {
                if (row.detectionValue == row.defaultValue) {
                    labeltext = '正常'
                } else {
                    labeltext = '异常'
                }
            }
            return labeltext
        },
        getDetectionIndexFormIndex(index) {
            return (
                (this.detectionIndexForm.pageNum - 1) * this.detectionIndexForm.pageSize + index + 1
            );
        },
        tabHandleClick(tab, event) {
            if (this.baseAdd.isDetail) {
                if (tab.name === "dectionDetail") {
                    this.detectionIndexForm.pageNum = 1
                    this.getlistDetectionVisit()
                } else {
                    this.tableData = []
                }
            }

        },
        //获取指标录入列表
        getlistDetectionVisit() {
            listDetectionVisit(this.detectionIndexForm).then(
                (response) => {
                    if (response.rows.length > 0) {
                        this.listDetectionVisit = response.rows
                        this.Listtotal = response.total;
                        console.log(this.Listtotal)
                        this.loading = false;
                    } else {
                        this.listDetectionVisit = []
                        this.Listtotal = 0;
                        this.loading = false;
                    }
                }
            )
        },
        getDetection(obj, arr) {//根据检测指标id 获取选项值
            let that = this
            let detectionId = obj.detectionId
            if (detectionId) {
                getDetection(detectionId).then((response) => {
                    let data = response.data;
                    arr[0].valueStr = data.valueStr
                    this.tableData = arr
                });
            }
        },
        getIndex(index) {
            return (this.queryParams.pageNum - 1) * this.queryParams.pageNum + index + 1;
        },
        getValueStr(str) {//转换获取选项值集合
            if (str) {
                console.log(str)
                return str.split(',')
            }
        },
        /** 查询列表 */
        getDetectionList() {//查询未绑定设备的单项指标检测值
            let params = {
                pageNum: 1,
                pageSize: 9999,
            }
            listNotHaveDevice(
                params
            ).then((response) => {
                this.detectionType = response.data;

            });
        },
        /** 查询列表 */
        getDeviceList() {//或者设备集合
          console.log('getDeviceList',this.baseAdd)
            let params = {
                pageNum: 1,
                pageSize: 9999,
                deviceType: '1',
                status: '0',
                deptId:this.baseAdd.deptId
            }
            listDeviceDept(
                params
            ).then((response) => {
                this.deviceList = response.rows;

            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            if (this.queryParams.visitNum || this.queryParams.patientName) {
                this.getPatientList();
            }
        },
        addPackage() {//添加设备
            let that = this
            const deviceId = this.projectForm.deviceId;
            if (deviceId) {
                getDevice(deviceId).then((response) => {
                    let data = response.data;
                    let detections = data.detections
                    detections.forEach(function (item) {
                        item.visitNum = that.queryParams.visitNum
                        item.patientName = that.queryParams.patientName
                        item.patientId = that.queryParams.patientId
                        item.detectionValue = item.defaultValue
                        item.visitDetectionName = item.detectionName
                    });
                    this.changeList(detections)

                });
            }

        },
        changeList(packageArr) {//调用去重获取集合
            let that = this
            this.detectionArr = this.detectionArr.concat(packageArr)
            let array = this.uniqueFunc(this.detectionArr, 'detectionId')
            that.tableData = array


        },
        /** 数组对象去重 */
        uniqueFunc(arr, uniId) { //根据指标id去重
            const res = new Map();
            return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
        },
        addSingle() {//添加单项指标值
            let that = this
            const detectionId = this.projectForm.detectionId;
            if (detectionId) {
                getDetection(detectionId).then((response) => {
                    let data = response.data;
                    data.visitNum = that.queryParams.visitNum
                    data.patientName = that.queryParams.patientName
                    data.detectionValue = data.defaultValue
                    data.patientId = that.queryParams.patientId
                    data.visitDetectionName = data.detectionName
                    let arr0 = []
                    arr0[0] = data
                    this.changeList(arr0)
                });
            }
        },//单项
        submitEvent() {//提交新增
            let that = this
            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    that.imageLoading = true
                    console.log("dahh")
                    if (this.baseAdd.updateStatus) {
                        let params = this.tableData[0]
                        console.log(this.baseAdd)
                        console.log('this.tableData---', this.tableData)
                        updateDetectionVisit(params).then((response) => {
                            that.imageLoading = false
                            this.$modal.msgSuccess("修改成功");
                            this.$emit('refresh')
                        });
                    } else {
                        let params = that.tableData
                        console.log('this.tableData+++', this.tableData)
                        console.log(that.tableData)
                        if (that.tableData.length == 0) {
                            that.imageLoading = false
                            this.$message({
                                message: '请录入检测指标!',
                                type: 'warning'
                            });
                            return false
                        }
                        addDetectionVisit(params).then((response) => {
                            that.imageLoading = false
                            console.log(response)
                            if (response.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess("新增成功");
                            }


                        });
                    }
                }
            });
        },
        changeQueryparams() {
            let that = this
            this.queryParams.visitNum = this.patientItem.visitNum
            this.queryParams.patientName = this.patientItem.patientName
            this.queryParams.patientId = this.patientItem.patientId
            let Arr = that.tableData
            Arr.forEach(function (item) {
                item.visitNum = that.queryParams.visitNum
                item.patientName = that.queryParams.patientName
                item.patientId = that.queryParams.patientId
            });
            that.tableData = Arr
        },
        // 获取顾客登记列表
        getPatientList() {
            getVisit(this.queryParams).then(
                (response) => {
                    if (response.rows.length > 0) {
                        if (response.rows.length == 1) {
                            this.patientItem = response.rows[0];
                            this.patientItem.birthDate = parseInt((new Date() - new Date(this.parseTime(this.patientItem.birthDate))) / (1000 * 60 * 60 * 24 * 365))
                            //获取检测指标列表

                            this.changeQueryparams()
                        } else {
                            this.patientVisible = true
                            this.patientList = response.rows;
                            this.patientList.forEach(item => {
                                item.birthDate = parseInt((new Date() - new Date(this.parseTime(this.patientList.birthDate))) / (1000 * 60 * 60 * 24 * 365))
                            })
                            this.total = response.total;

                        }

                    } else {
                        // this.$modal.msgWarning("没找到对应的顾客！");
                        this.$confirm('没找到对应的顾客！请您自己搜索选择顾客', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                            .then((content) => {
                                console.log('content', content)
                            })
                            .catch((error) => {
                                console.log('error', error)
                            })

                    }


                }
            )
        },
        confirmPatient(row) {
            this.patientItem = row
            console.log('confirmPatient', row)
            this.patientVisible = false
            this.changeQueryparams()

        },

    },
};
</script>
<style scoped rel="stylesheet/scss"  lang="scss">
.el-form-item--small.el-form-item {
    margin-bottom: 0px;
}

::v-deep .el-input.is-disabled .el-input__inner {
    color: #606266;
}

::v-deep .el-input.is-disabled .el-input__inner {
    color: #1890ff !important;
}

.mt5 {
    margin-top: 5px;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

::v-deep input[type="number"] {
    -moz-appearance: textfield;
}

::v-deep .el-dialog {
    margin-top: 0 !important;
}

.detectionAddbtn {
    background-color: #f3a4a1;
    color: white;
    margin: 0 auto;
    display: block;
}
</style>
